package au.com.mason.propertyTracker.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import au.com.mason.propertyTracker.domain.Search;

@Repository
public class MonitorDAO extends HibernateDaoSupport {

	public MonitorDAO() {}
	
	public Object findById(int id) {
		return getHibernateTemplate().get(Search.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public List findAll() {
        DetachedCriteria criteria = getCriteria();

        return getHibernateTemplate().findByCriteria(criteria);
    }

	protected DetachedCriteria getCriteria() {
		return DetachedCriteria.forClass(Search.class);
	}
	
	public Serializable save(Object object) {
		if (object.getClass().getName().startsWith(Search.class.getName())) {
			return getHibernateTemplate().save(object);
		}
		
		throw new IllegalArgumentException("expect object of type " + Search.class);
	}
	
	public void update(Object object) {
		if (object.getClass().getName().startsWith(Search.class.getName())) {
			getHibernateTemplate().update(object);
		}
		else {
			throw new IllegalArgumentException("expect object of type " + Search.class);
		}
	}
	
	public void delete(Object object) {
		if (object.getClass().getName().startsWith(Search.class.getName())) {
			getHibernateTemplate().delete(object);
		}
		else {
			throw new IllegalArgumentException("expect object of type " + Search.class);
		}
	}
	
	public List<Search> getMonitors(boolean rental, boolean full) {
	 	String sql = "from Monitor";
	 	if (rental) {
	 		sql += " where rental = true";
	 	}
	 	else {
	 		sql += " where rental = false";
	 	}
	 	if (full) {
	 		sql += " and includeFull = true";
	 	}
	 	else {
	 		sql += " and includeFull = false";
	 	}

	 	Query query = getSession().createQuery(sql);
       	
       	return query.list();
	}	
	
}
